<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form label-width="60px">
        <el-form-item label="状态" style="width: 200px" class="filter-item">
          <el-input />
        </el-form-item>
        <el-form-item label="时间" style="width: 200px" class="filter-item">
          <el-input />
        </el-form-item>
        <el-form-item label="业务员" style="width: 200px" class="filter-item">
          <el-input />
        </el-form-item>
        <el-button v-waves style="margin-left: 20px" class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
          查询
        </el-button>
        <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleUpdate(row)">
          添加
        </el-button>
      </el-form>
    </div>

    <el-table
      :data="tableData"
      style="width: 100%"
    >
      <!--列表展开-->
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-form label-position="left" inline class="demo-table-expand">
            <el-form-item label="应收">
              <span>{{ props.row.receive }}</span>
            </el-form-item>
            <el-form-item label="实收">
              <span>{{ props.row.really }}</span>
            </el-form-item>
            <el-form-item label="优惠">
              <span>{{ props.row.sale }}</span>
            </el-form-item>
            <el-form-item label="欠款">
              <span>{{ props.row.arrears }}</span>
            </el-form-item>
            <el-form-item label="退款">
              <span>{{ props.row.refund }}</span>
            </el-form-item>
            <el-form-item label="课时">
              <span>{{ props.row.hours }}</span>
            </el-form-item>
            <el-form-item label="单价">
              <span>{{ props.row.price }}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column
        label="名称"
        prop="classes"
      />
      <el-table-column
        label="学生"
        prop="student"
      />
      <el-table-column
        label="业务员"
        prop="salesman"
      />
      <el-table-column
        label="状态"
        prop="status"
      />
      <el-table-column
        label="班级类型"
        prop="category"
      />
      <el-table-column
        label="缴费类型"
        prop="money"
      />
      <el-table-column label="操作" align="center" min-width="200px" class-name="small-padding fixed-width">
        <template>
          <el-link type="primary" style="width: 20%">
            退款
          </el-link>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
    <!--新增-->
    <el-dialog title="添加课程" :visible.sync="dialogFormVisible">
      <el-form label-position="left" label-width="80px" style="width: 400px; margin-left:50px;">
        <el-form-item label="学生/客户">
          <el-select placeholder="请选择" />
        </el-form-item>
        <el-form-item label="课程">
          <el-select placeholder="请选择" />
        </el-form-item>
        <el-form-item label="业务人员">
          <el-select placeholder="请选择" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select placeholder="请选择">
            <el-option label="新签" value="shanghai" />
            <el-option label="续签" value="beijing" />
          </el-select>
        </el-form-item>
        <el-form-item label="班级类型">
          <el-select placeholder="请选择">
            <el-option label="一对一" value="shanghai" />
            <el-option label="集体" value="beijing" />
          </el-select>
        </el-form-item>
        <el-form-item label="课时">
          <el-input />
        </el-form-item>
        <el-form-item label="单价">
          <el-input />
        </el-form-item>
        <el-form-item label="优惠金额">
          <el-input />
        </el-form-item>
        <el-form-item label="实际付款">
          <el-input />
        </el-form-item>
        <div class="dialog-footer">
          <el-button type="primary">
            添加
          </el-button>
        </div>
      </el-form>
    </el-dialog>

  </div>
</template>

<script>
import { fetchList, fetchPv, createArticle, updateArticle } from '@/api/article'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

const calendarTypeOptions = [
  { key: 'CN', display_name: 'China' },
  { key: 'US', display_name: 'USA' },
  { key: 'JP', display_name: 'Japan' },
  { key: 'EU', display_name: 'Eurozone' }
]

// arr to obj, such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  name: 'Manage',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  data() {
    return {
      tableData: [{
        classes: '现代艺术',
        category: '一对一',
        student: '张三',
        status: '正常',
        salesman: '张佳林',
        money: '欠款',
        receive: '200',
        really: '100',
        sale: '8',
        arrears: '57',
        refund: '0',
        price: '100',
        hours: '4'
      }, {
        classes: '古典音乐',
        category: '一对一',
        student: '李四',
        status: '正常',
        salesman: '张佳林',
        money: '结款',
        receive: '555',
        really: '555',
        sale: '0',
        arrears: '0',
        refund: '0',
        price: '555',
        hours: '10'
      }, {
        classes: '艺术体操',
        category: '集体',
        student: '王五',
        status: '正常',
        salesman: '张佳林',
        money: '退款',
        receive: '666',
        really: '700',
        sale: '34',
        arrears: '0',
        refund: '0',
        price: '700',
        hours: '12'
      }],
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        importance: undefined,
        title: undefined,
        type: undefined,
        sort: '+id'
      },
      importanceOptions: [1, 2, 3],
      calendarTypeOptions,
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      temp: {
        id: undefined,
        importance: 1,
        remark: '',
        timestamp: new Date(),
        title: '',
        type: '',
        status: 'published'
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: 'Edit',
        create: 'Create'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        type: [{ required: true, message: 'type is required', trigger: 'change' }],
        timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
        title: [{ required: true, message: 'title is required', trigger: 'blur' }]
      },
      downloadLoading: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        this.list = response.data.items
        this.total = response.data.total

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        importance: 1,
        remark: '',
        timestamp: new Date(),
        title: '',
        status: 'published',
        type: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.temp.id = parseInt(Math.random() * 100) + 1024 // mock a id
          this.temp.author = 'vue-element-admin'
          createArticle(this.temp).then(() => {
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Created Successfully',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
          updateArticle(tempData).then(() => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Update Successfully',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row, index) {
      this.$notify({
        title: 'Success',
        message: 'Delete Successfully',
        type: 'success',
        duration: 2000
      })
      this.list.splice(index, 1)
    },
    handleFetchPv(pv) {
      fetchPv(pv).then(response => {
        this.pvData = response.data.pvData
        this.dialogPvVisible = true
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
        const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>
<style>
  .demo-table-expand {
    font-size: 0;
  }
  .demo-table-expand label {
    width: 80px;
    color: #99a9bf;
  }
  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
  }
</style>
